﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace anydata.Models
{
    public class OperateResult
    {
        public bool success { get; set; }
        public object data { get; set; }
        public string msg { get; set; }
        public int code { get; set; }
        public JsonResult Result()
        {
            return new JsonResult(this);
        }

        public static OperateResult Faild(string error)
        {
            return new OperateResult()
            {
                success = false,
                data = new object(),
                msg = error,
                code = 500,
            };
        }
        public static OperateResult Faild(string msg, object error)
        {
            return new OperateResult()
            {
                success = false,
                data = error,
                msg = msg,
                code = 500,
            };
        }

        public static OperateResult Success(object? data)
        {
            if(data is string)
            {
                var str = (string)data;
                if (str.Contains("{"))
                {
                    data = JToken.Parse(str);
                }
                else
                {
                    data = str;
                }
            }
            return new OperateResult()
            {
                data = data ?? new object(),
                success = true,
                msg = "成功",
                code = 200,
            };      
        }

    }


    public class OperateResult<T> : OperateResult where T : class
    {

        public new T data { get; set; }
        public static OperateResult<T> Success(T? data)
        {
            return new OperateResult<T>()
            {
                data = data,
                success = true,
                msg = "成功",
                code = 200,
            };
        }

        public static new OperateResult<T> Faild(string error)
        {
            return new OperateResult<T>()
            {
                success = false,
                data = default!,
                msg = error,
                code = 500,
            };
        }

    }

}
